package com.atwisdom.star.core.dsl.modelClass.consume.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.UuidTool;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.PageInfo;
import com.atwisdom.star.core.dao.pojo.modelClass.consume.ConsumeInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.consume.ConsumeInstanceHistory;
import com.atwisdom.star.core.dao.pojo.modelClass.consume.ConsumeModel;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicModel;
import com.atwisdom.star.core.dao.service.modelClass.consume.ConsumeInstanceHistoryService;
import com.atwisdom.star.core.dao.service.modelClass.consume.ConsumeInstanceService;
import com.atwisdom.star.core.dao.service.modelClass.consume.ConsumeModelService;
import com.atwisdom.star.core.dsl.cache.ModelCacheDslService;
import com.atwisdom.star.core.dsl.modelClass.consume.ConsumeInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.utils.QueryBuilder;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ConsumeInstanceDslServiceImpl implements ConsumeInstanceDslService {

    private ConsumeModelService consumeModelService;
    private ConsumeInstanceService consumeInstanceService;
    private ConsumeInstanceHistoryService consumeInstanceHistoryService;

    private HierInstanceDslServiceImpl hierInstanceDslService;

    private QueryBuilder queryBuilder;

    private ModelCacheDslService modelCacheDslService;

    @Autowired
    public void setModelCacheDslService(ModelCacheDslService modelCacheDslService) {
        this.modelCacheDslService = modelCacheDslService;
    }

    @Autowired
    public void setConsumeModelService(ConsumeModelService consumeModelService) {
        this.consumeModelService = consumeModelService;
    }

    @Autowired
    public void setConsumeInstanceService(ConsumeInstanceService consumeInstanceService) {
        this.consumeInstanceService = consumeInstanceService;
    }

    @Autowired
    public void setConsumeInstanceHistoryService(ConsumeInstanceHistoryService consumeInstanceHistoryService) {
        this.consumeInstanceHistoryService = consumeInstanceHistoryService;
    }

    @Autowired
    public void setHierInstanceDslService(HierInstanceDslServiceImpl hierInstanceDslService) {
        this.hierInstanceDslService = hierInstanceDslService;
    }

    @Autowired
    public void setQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
    }


    /**
     * Consume实例的查询操作-》查询全部摘要（通用）
     * 选择字段为“摘要字段”，
     * 默认按照className,updateTime排序
     * published为true
     * @return 返回搞要列表
     */
    @Override
    public List<JSONObject> queryAllInfo() {
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<ConsumeInstance> list = consumeInstanceService.list();
            List<JSONObject> jsonObjectList = new ArrayList<>();
            list.forEach(ins-> jsonObjectList.add(ins.getInfoJsonObject()));
            return jsonObjectList;
        } catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }

    /**
     * Consume实例的查询操作-》分页查询全部摘要（通用）
     * 选择字段为“摘要字段”，
     * 默认按照className,updateTime排序
     * published为true
     * @param pageNumber 页号
     * @param pageSize 条数
     * @param orderBy 排序字段
     * @return 返回全部搞要列表
     */
    @Override
    public PageInfo queryAllInfoByPage(int pageNumber, int pageSize, String orderBy) {
        try {
            Page<ConsumeInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,true);
        }catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }

    /**
     * Consume实例的查询操作-》查询全部数据（通用）
     * 选择字段为“摘要字段”，
     * 默认按照className,updateTime排序
     * published为true
     * @return 返回全部列表
     */
    @Override
    public List<JSONObject> queryAll() {
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildOrderBy(queryWrapper,null,"className,updateTime");
            List<ConsumeInstance> list = consumeInstanceService.list();
            return this.getConsumeInsJsonObjectList(list);
        }catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }

    /**
     * Consume实例的查询操作-》分页无条件查询模型信息
     * 选择字段为“所有字段”，
     * 默认按照className,updateTime排序
     * published为true
     * @param pageNumber 页号
     * @param pageSize 条数
     * @param orderBy 排序字段
     * @return 返回分页列表
     */
    @Override
    public PageInfo listAllByPage(int pageNumber,int pageSize,String orderBy) {
        try {
            Page<ConsumeInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,false);
        }catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }

    /**
     * Consume实例的查询操作-》查询模型
     * 默认按照className,updateTime,id排序
     * published为true
     * @param condition 查询条件
     * @param className 类名
     * @param orderBy 排序字段
     * @return 返回列表
     */
    @Override
    public List<JSONObject> query(String condition,String className,String orderBy) {
        try{
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForConsume(condition,className);
            orderBy = this.transformOrderByForConsume(condition,className,orderBy);
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            List<ConsumeInstance> list = consumeInstanceService.list(queryWrapper);
            return this.getConsumeInsJsonObjectList(list);
        }catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }

    /**
     * Consume实例的查询操作-》查询全部数据（通用）
     * published为true
     * @param condition 查询条件
     * @param className 类名
     * @return 返回列表
     */
    @Override
    public List<ConsumeInstance> queryByClassName(String className,String condition) {
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published", true);
            queryWrapper.eq("className", className);
            condition = this.transformConditionForConsume(condition,className);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            return consumeInstanceService.list(queryWrapper);
        }catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }

    @Override
    public ConsumeInstance queryInsById(Long id){
        return consumeInstanceService.getById(id);
    }

    /**
     * Consume实例的查询操作-》按条件分页查询实例摘要
     * 默认按照className,updateTime,id排序
     * published为true
     * @param pageNumber 页号
     * @param pageSize 条数
     * @param orderBy 排序字段
     * @param condition 查询条件
     * @param className 类名
     * @return 返回列表
     */
   public PageInfo queryInfoByPage(int pageNumber,int pageSize, String condition,String className,String orderBy){
       try {
           Page<ConsumeInstance> pageInfo = new Page<>(pageNumber, pageSize);
           condition = queryBuilder.transformOperator(condition);
           condition =  this.transformConditionForConsume(condition,className);
           orderBy = this.transformOrderByForConsume(condition,className,orderBy);
           QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
           queryWrapper.eq("published", true);
           queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
           queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
           return getPageInfoResult(pageInfo, queryWrapper,true);
       }catch (DataAccessException e) {
           // 更具体地捕获数据库相关的异常
           throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
       } catch (Exception e) {
           // 捕获其他未预期的异常
           throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
       }
    }

    /**
     * Consume实例的查询操作-》按条件分页查询实例
     * 默认按照className,updateTime,id排序
     * published为true
     * @param pageNumber 页号
     * @param pageSize 条数
     * @param orderBy 排序字段
     * @param condition 查询条件
     * @param className 类名
     * @return 返回列表
     */
    public PageInfo queryByPage(int pageNumber,int pageSize, String condition,String className,String orderBy){
        try {
            Page<ConsumeInstance> pageInfo = new Page<>(pageNumber, pageSize);
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForConsume(condition,className);
            orderBy =   this.transformOrderByForConsume(condition,className,orderBy);
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,false);
        }catch (DataAccessException e) {
            // 更具体地捕获数据库相关的异常
            throw new BusinessException("999999", "查询所有模型信息时遇到数据库错误！",e);
        } catch (Exception e) {
            // 捕获其他未预期的异常
            throw new BusinessException("999999", "无条件查询所有模型信息时发生未知错误！",e);
        }
    }
    /**
     * 根据ID查询
     * @return
     */
    @Override
    public JSONObject queryById(Long id) {
        ConsumeInstance consumeInstance = consumeInstanceService.getById(id);
        ConsumeModel consumeModel = modelCacheDslService.queryModel(ModelType.Consume.getCode(), consumeInstance.getClassName());
        return consumeInstance.getInsJsonObject(consumeModel);

    }

    /**
     * 根据id数组获取实例数据
     *
     * @param ids 主键ids
     * @return 返回实例
     */
    public List<JSONObject> queryByIds(List<Long> ids) {
        LambdaQueryWrapper<ConsumeInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ConsumeInstance::getId,ids);
        List<ConsumeInstance> instanceList = consumeInstanceService.list(wrapper);
        return getConsumeInsJsonObjectList(instanceList);

    }

    /**
     * Consume实例的编辑操作-》添加模型
     *
     * @param type 参数
     * @param className 参数
     * @param name 参数
     * @return 返回值
     */
    @Override
    public JSONObject add(String type, String className,String name,JSONObject values) {
        if (existModel(type, className)) {
            if(values==null){
                values = new JSONObject();
            }

            try {
                ConsumeModel consumeModel = this.modelCacheDslService.queryModel(ModelType.Consume.getCode(), className);
                JSONObject insJsonObject = new JSONObject();
                insJsonObject.put("type", type);
                insJsonObject.put("name", name);
                insJsonObject.put("className", className);
                insJsonObject.put("published", true);
                insJsonObject.put("version", consumeModel.getVersion());
                insJsonObject.put("values", values);
                insJsonObject.put("web", new JSONObject());
                insJsonObject.put("others", new JSONObject());
                ConsumeInstance instance = new ConsumeInstance(consumeModel, insJsonObject);
                this.consumeInstanceService.save(instance);
                return instance.getInsJsonObject(consumeModel);
            } catch (Exception ex) {
                throw new BusinessException("999999", "添加模型失败！", ex);
            }
        } else {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
    }

    /**
     * 添加实例
     *
     * @param type      参数
     * @param className 参数
     * @param name      参数
     * @param values    参数
     * @param web web参数
     * @return 返回值
     */
    @Override
    public JSONObject add(String type, String className, String name,JSONObject values, JSONObject web) {
        ConsumeModel consumeModel = this.modelCacheDslService.queryModel(ModelType.Consume.getCode(), className);
        if(values==null){
            values = new JSONObject();
        }
        try {
            JSONObject insJsonObject = new JSONObject();
            insJsonObject.put("type", type);
            String uuid32 = UuidTool.getUUID32();
            insJsonObject.put("name", StrUtil.isNotBlank(name)? name:uuid32);
            insJsonObject.put("className", className);
            insJsonObject.put("published", true);
            insJsonObject.put("version", consumeModel.getVersion());
            insJsonObject.put("values", values);
            insJsonObject.put("web", CollectionUtil.isEmpty(web)? new JSONObject():web);
            insJsonObject.put("others", new JSONObject());
            ConsumeInstance instance = new ConsumeInstance(consumeModel, insJsonObject);
            this.consumeInstanceService.save(instance);
            return instance.getInsJsonObject(consumeModel);
        } catch (Exception ex) {
            throw new BusinessException("999999", "添加模型失败！", ex);
        }
    }

    /**
     * Consume实例的编辑操作-》保存新实例
     * @param newInstance 新实例
     * @return 返回添加后的实例
     */
    public ConsumeInstance add(ConsumeInstance newInstance){
        if (StrUtil.isBlank(newInstance.getName())) {
            newInstance.setName(UuidTool.getUUID32());
        }
        this.consumeInstanceService.save(newInstance);
        return newInstance;
    }

    /**
     * Consume实例的编辑操作-》更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObject 参数
     * @return 返回值
     */
    @Override
    public JSONObject updateById(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        if(StringUtils.isBlank(id)){
            throw new BusinessException("999999", "更新id为空操作失败！");
        }
        try {
            ConsumeInstance sourceInstance = consumeInstanceService.getById(id);
            if(sourceInstance==null){
                throw new BusinessException("999999", "要更新实例不存在，操作失败！");
            }

            ConsumeModel model = this.modelCacheDslService.queryModel(ModelType.Consume.getCode(), sourceInstance.getClassName());
            ConsumeInstance consumeInstance =new ConsumeInstance(model,jsonObject,sourceInstance.getValues());
            consumeInstanceService.getBaseMapper().updateById(consumeInstance);

            //添加历史
            ConsumeInstanceHistory consumeInstanceHistory = new ConsumeInstanceHistory();
            BeanUtils.copyProperties(consumeInstance,consumeInstanceHistory);
            consumeInstanceHistory.setId(null);
            this.consumeInstanceHistoryService.save(consumeInstanceHistory);
            return consumeInstance.getInsJsonObject(model);
        }catch (Exception ex){
            throw new BusinessException("999999", "更新模型实例失败！");
        }
    }

    public void updateFieldNullById(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        Long id = jsonObject.getLong("id");
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject values = jsonObject.getJSONObject("values");
        JSONObject features = logicModel.fetchFeatures();
        UpdateWrapper<ConsumeInstance> updateWrapper = new UpdateWrapper<>();
        // 遍历 JSONObject 对象
        for (String key : features.keySet()) {
            String v = values.getString(key);
            if(StringUtils.isBlank(v)){
                updateWrapper.set(key, null);
            }
        }
        updateWrapper.eq("id",id);
        consumeInstanceService.update(updateWrapper);
    }

    /**
     * Consume实例的编辑操作-》更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObjectList 参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> updateByIds(List<JSONObject> jsonObjectList) {
        List<JSONObject> resultJsonList = new ArrayList<>();
        jsonObjectList.forEach(j->{
            JSONObject jsonObject = this.updateById(j);
            resultJsonList.add(jsonObject);

        });
        return resultJsonList;
    }


    /**
     * Consume实例的编辑操作-》按类型和类名更新模型实例（配置阶段）
     * @param jsonObject 类型
     * @return 返回模型记录
     */
    @Override
    public List<JSONObject> updateClassName(JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        String className = jsonObject.getString("className");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "更新模型实例：type,className都不能为空！");
        }

        if (!this.existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在，更新模型实例失败！");
        }

        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("type", type);
            queryWrapper.eq("published", true);
            List<ConsumeInstance> instances = this.consumeInstanceService.list(queryWrapper);
            List<JSONObject> resList = new ArrayList<>();
            instances.forEach(ins->{
                jsonObject.put("id",ins.getId());
                JSONObject upJsonObject = this.updateById(jsonObject);
                resList.add(upJsonObject);
            });
            return resList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "更新模型类型和类名", ex);
        }
    }


    /**
     * Consume实例的编辑操作-》按ids删除模型,同时删除hier中被关联的数据
     * @param ids id列表
     * @return 返回结果
     */
    public boolean deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，删除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            //删除实例
            this.consumeInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByLinkIdList(ModelType.Consume.getCode(), ids);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }
    }

    /**
     * Consume实例的编辑操作-》接className删除同时删除被关联的数据
     * 1、删除实例、2、删除历史 3、更新redis
     *
     * @param className 模型类名
     * @return 返回值
     */
    @Override
    public boolean deleteByClassName(String className)  {
        if (StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "模型类名称不能为空,删除模型实例失败！");
        }
        //删除缓存
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("published", true);
            //删除模型
            this.consumeInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByLinkClassName(ModelType.Consume.getCode(), className);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", String.format("删除模型%s失败!", className), ex);
        }
    }

    /**
     * Consume实例的编辑操作-》接className批量删除同时删除被关联的数据
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean deleteByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型实例失败！");
        }
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除实例
            this.consumeInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByLinkClassNameList(ModelType.Resource.getCode(), classNames);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型失败！");
        }
    }

    /**
     * Consume实例的编辑操作-》按Id 废除模型
     * @param ids 参数
     * @return 返回结果
     */
    public boolean repealByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，废除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<ConsumeInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            //删除实例
            this.consumeInstanceService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }

    }

    /**
     * Consume实例的编辑操作-》批量废除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean repealByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型失败！");
        }
        try {
            QueryWrapper<ConsumeModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除模型
            this.consumeModelService.remove(queryWrapper);
            return true;
        }catch (Exception ex){
            throw new BusinessException("999999", "模型类名称列表删除模型实例失败！");
        }
    }

    /**
     * Consume实例的查询操作-》获取分页查询
     * @param pageInfo 分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<ConsumeInstance> pageInfo, QueryWrapper<ConsumeInstance> queryWrapper,boolean isInfo) {
        Page<ConsumeInstance> queryPage = consumeInstanceService.page(pageInfo, queryWrapper);
        List<ConsumeInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if(isInfo){
            jsonObjectList = this.getConsumeInsInfoJsonObjectList(records);
        }else{
            jsonObjectList = this.getConsumeInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * Consume实例的查询操作-》检查模型是否存在
     * @param type 类型
     * @param className 类名称
     * @return 返回是否存，true 存在，false 不存在
     */
    private boolean existModel(String type, String className) {
        QueryWrapper<ConsumeModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq("published", true);
        long count = this.consumeModelService.count(queryWrapper);
        return count > 0;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getConsumeInsInfoJsonObjectList(List<ConsumeInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            JSONObject infoJsonObject = ins.getInfoJsonObject();
            jsonList.add(infoJsonObject);

        });
        return jsonList;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getConsumeInsJsonObjectList(List<ConsumeInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            ConsumeModel consumeModel = this.modelCacheDslService.queryModel(ModelType.Consume.getCode(), ins.getClassName());
            JSONObject insJsonObject = ins.getInsJsonObject(consumeModel);
            jsonList.add(insJsonObject);
        });
        return jsonList;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition            参数
     * @param className            参数
     */
    public String transformConditionForConsume(String condition, String className) {
        if (StringUtils.isBlank(condition)) {
            return condition;
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }
        if (StringUtils.isBlank(className)) {
            return condition;
        }
        if (StringUtils.isNotBlank(className) && StringUtils.isNotBlank(condition)) {
            ConsumeModel consumeModel = modelCacheDslService.queryModel(ModelType.Consume.getCode(), className);
            if (consumeModel != null) {
                List<JSONObject> featureProperties = consumeModel.fetchFeatureProperties();
                for (JSONObject item : featureProperties) {
                    String name = item.getString("name");
                    String code = item.getString("code");
                    // condition = condition.replaceAll(name, code);
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name, code);
                    log.info("condition = {}", condition);
                }

                JSONArray statusProperties = consumeModel.getStatusProperties();
                if(statusProperties!=null){
                    for (Object obj : statusProperties) {
                        JSONObject item = JSONObject.parseObject(JSON.toJSONString(obj));
                        String name = item.getString("name");
                        String code = item.getString("code");
                        condition = condition.replaceAll(name, code);
                    }
                }
                List<JSONObject> featureNoProperties = consumeModel.fetchNonFeaturesProperties();
                for (JSONObject item : featureNoProperties) {
                    String name = item.getString("name");
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name,
                            java.util.regex.Matcher.quoteReplacement("JSON_EXTRACT(insValues,'$.")+name+
                                    "')");
                }
            }
        }
        return condition;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 取className 条件
     * @param className 类名
     * @param orderBy   排序参数
     */
    public String transformOrderByForConsume(String condition, String className, String orderBy) {
        if (StringUtils.isBlank(orderBy)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }

        if (StringUtils.isBlank(className)) {
            return orderBy;
        }
        orderBy = orderBy.replaceAll(" ", "");
        ConsumeModel consumeModel = modelCacheDslService.queryModel("consume", className);
        List<JSONObject> featureProperties = consumeModel.fetchFeatureProperties();
        for (JSONObject item : featureProperties) {
            String name = item.getString("name");
            String code = item.getString("code");
            orderBy = orderBy.replaceAll(name, code);
        }
        return orderBy;
    }

}
